package main

import (
	"chat/lib/chat"
	"chat/session"
	"encoding/json"
	"log"
	"time"

	"golang.org/x/net/websocket"
)

func agent(c *websocket.Conn) {
	defer func() {
		if x := recover(); x != nil {
			log.Println(x)
		}
	}()

	sess := session.New(c)
	session.Register(sess)
	defer func() {
		session.UnRegister(sess.ID)
		sess.Close()
	}()

	//notify chat history
	data, _ := json.Marshal(chat.Mgr.History())
	sess.Send(data)
	for {
		c.SetReadDeadline(time.Now().Add(60 * time.Second))
		var msg string
		if err := websocket.Message.Receive(c, msg); err != nil {
			log.Println("Receive error err: ", err)
			return
		}
		sess.Receive([]byte(msg))
	}
}
